package com.seckill.rabbitmq;

import com.seckill.pojo.SeckillGoods;
import com.seckill.pojo.User;
import com.seckill.service.IGoodsService;
import com.seckill.service.IOrderService;
import com.seckill.utils.JSONUtil;
import com.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author levi
 * @version 1.0
 * @datetime 2021/9/6 21:51
 * @decription 消息接收（消费者）
 **/
@Service
@Slf4j
public class MQReceiverService {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 下单
     *
     * @param message
     */
    @RabbitListener(queues = "seckillQueue")
    public void receiveSeckillMessage(String message) {
        log.info("接收消息：" + message);
        SeckillMessage seckillMessage = JSONUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        // 判断库存（这里是mysql库存判断，之前是redis）
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goods.getStockCount() < 1) {
            return;
        }
        // 查看是否重复秒杀
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.opsForValue().get("orders:" + user.getId() + ":" + goodsId);
        if (seckillGoods != null) {
            return;
        }
        orderService.seckill(user, goods);
    }
}
